import React, { useState, useEffect, useRef } from "react";
import { Form, Button, Input, Affix, Select, message, Space, Switch, Drawer, Row, Col, Modal, Radio, Checkbox } from "antd";
import { MinusCircleOutlined, PlusCircleOutlined, PlusOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
import cmdbres from "@/data/cmdbres";
import request, {requestIAM} from '@/utils/request';
import { actionTypeOption, timeOptions, periodOptions, periodMinuteOptions, periodHourOptions, periodDayOptions } from './options';
import hcpUtils from "@/utils/hcpUtils";

const user = hcpUtils.getUser();
const CreateRelation = ({ history, info, visible, setVisible, onCreateFinish }) => {
	const [form] = Form.useForm();
    const [loading, setLoading] = useState(false);
    const [timeOptionsState, setTimeOptionsState] = useState(timeOptions);
    const [executionMethod, setExecutionMethod] = useState(actionTypeOption[0].value);
    const [periodOption, setPeriodOption] = useState(periodHourOptions);

    useEffect(() => {
        if(visible && info?.task) {
            const task = info.task;
            if(task.actionType) setExecutionMethod(task.actionType);
            if(task.actionType == '定时') {
                form.setFieldsValue({
                    actionType: task.actionType,
                    executionTime: cron[2]?.split(',')?.map(Number),
                    repetitionCycle: cron[5]?.split(',')?.map(Number),
                })
            } else {
                form.setFieldsValue({
                    actionType: task.actionType,
                    periodUnit: task.periodUnit,
                    periodValue: task.periodValue,
                })
            }
        }
    }, [visible])

    const changeActionType = (e) => {
        setExecutionMethod(e.target.value);
        form.setFieldsValue({
            periodUnit: '小时',
            periodValue: undefined
        });
        setPeriodOption(periodHourOptions)
    };

    const changeExecutionTime = (checkedValues) => {
        const arr = JSON.parse(JSON.stringify(timeOptionsState));
        if (checkedValues?.length == 4) {
            arr.map(item => item.disabled = !checkedValues.includes(item.value));
        } else {
            arr.map(item => item.disabled = false);
        }
        setTimeOptionsState(arr);
    };

    const changePeriodType = (value) => {
        form.setFieldsValue({
            periodUnit: value,
            periodValue: undefined
        });
        if (value == '分') {
            setPeriodOption(periodMinuteOptions)
        }
        else if (value == '小时') {
            setPeriodOption(periodHourOptions)
        }
        else if (value == '天') {
            setPeriodOption(periodDayOptions)
        }
    }

	const onFinish = async (fieldsValue) => {
        setLoading(true);
        let param = Object.assign({}, fieldsValue);
        if(param.actionType == '定时') {
            param.actionCron = '0 0 ' + param.executionTime?.toString() + ' ? * ' + param.repetitionCycle?.toString();
            delete param.executionTime;
            delete param.repetitionCycle;
        }

		let res = await request({
			...cmdbres.autoExecuteModuleAssociateRule(info.ruleId,1,user.staffName),
			data: param
		});
		setLoading(false);
		if (res && res.code == 200) {
			setVisible(false);
			message.success("保存成功！");
			if (typeof onCreateFinish == "function") onCreateFinish(res);
		}
	};

    const handleClose = () => {
        setVisible(false);
    }

    return (
        <Modal 
            title={"执行规则"}
            className="hcp-modal-md"
            onCancel={handleClose}
            visible={visible}
            footer={null}
            destroyOnClose
            afterClose={() => {
                form.resetFields();
            }}
        >
            <Form
                form={form}
                labelCol={{ span: 5}}
                wrapperCol={{ span: 17 }}
                name="basic"
                onFinish={onFinish}
            >
                <Form.Item 
                    label="执行方式" 
                    name='actionType'
                    rules={[
                        { required: true, message: '请选择执行方式' },
                    ]}
                    initialValue={executionMethod}
                >
                    <Radio.Group onChange={changeActionType}>
                        {actionTypeOption.map(item=> {
                            return (
                                <Radio key={item.value} value={item.value}>{item.label}</Radio>
                            )
                        })}
                    </Radio.Group>
                </Form.Item>
                {
                    executionMethod == '定时' &&
                    <>
                        <Form.Item label="执行时间" name='executionTime'
                            rules={[
                                { required: true, message: '请选择执行时间' },
                            ]}>
                            <Checkbox.Group 
                                options={timeOptionsState} 
                                onChange={changeExecutionTime} 
                                style={{ width: 550 }}
                            >
                            </Checkbox.Group>
                        </Form.Item>
                        <Form.Item label="重复周期" name='repetitionCycle'
                            rules={[
                                { required: true, message: '请选择重复周期' },
                            ]}>
                            <Checkbox.Group options={periodOptions}>
                            </Checkbox.Group>
                        </Form.Item>
                    </>
                }
                {
                    executionMethod == '周期' &&
                    <>
                        <Form.Item label="重复周期单位" name='periodUnit'
                            rules={[
                                { required: true, message: '请选择重复周期单位' },
                            ]}>

                            <Select 
                                style={{ width: 300 }} 
                                defaultValue={'小时'} 
                                onChange={changePeriodType}
                            >
                                <Select.Option value={'天'}>天</Select.Option>
                                <Select.Option value={'小时'}>小时</Select.Option>
                                <Select.Option value={'分'}>分</Select.Option>
                            </Select>
                            <Row style={{ marginTop: 10 }}>
                                <ExclamationCircleOutlined 
                                    style={{ color: '#439FE1', marginTop: 3, marginRight: 3 }} 
                                />
                                <span style={{ color: '#999999' }}>
                                    任务未完成时不自动执行下次任务
                                </span>
                            </Row>
                        </Form.Item>
                        <Form.Item label="重复周期值" name='periodValue'
                            rules={[
                                { required: true, message: '请选择重复周期值' },
                            ]}>

                            <Radio.Group>
                                {
                                    periodOption?.map((item, index) => {
                                        return <Radio key={item.value} value={item.value}>{item.label}</Radio>
                                    })
                                }
                            </Radio.Group>

                        </Form.Item>
                    </>
                    }
                <div className="hcp-modal-body-footer">
                    <Form.Item wrapperCol={{ span: 24 }}>
                        <Button onClick={handleClose}>取消</Button>
                        <Button type="primary" htmlType="submit" loading={loading}>确定</Button>
                    </Form.Item>
                </div>
            </Form>
        </Modal>
    );
};

export default CreateRelation;
